package com.shw.controller;

import com.shw.bean.User;
import com.shw.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * Created by shw on 2018-03-23.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    ModelAndView modelAndView=new ModelAndView();

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login")
    public ModelAndView login(User user, String code, HttpSession session) {
        //获取当前执行的用户
        Subject currentUser = SecurityUtils.getSubject();
        //获取验证码并把字母转换为小写
        String code1 = String.valueOf(session.getAttribute("code"));

        //判断验证码是否正确，不正确直接到登录界面
        if (code1 == null || !code1.toLowerCase().equals(code)) {
           modelAndView.setViewName("login");
           modelAndView.addObject("msg","验证码不正确！！！");
           return modelAndView;
        }
        //让我们登陆当前的用户，这样就可以检查角色和权限

        System.out.println("----------->验证码正确");
        if (!currentUser.isAuthenticated()) {
            //当前用户没有登陆
            //把用户名和密码封装成usernamepasswordToken对象
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
            //是否记住我
            token.setRememberMe(true);
            try {

                //将第一次认证的用户名和密码存入session中
                session.setAttribute("username",user.getUsername());
                //调用login方法进行登陆
                currentUser.login(token);

            } catch (AuthenticationException e) {
                //在这里捕获更多的异常，返回到登陆界面
                modelAndView.setViewName("login");
                modelAndView.addObject("msg","用户名密码不正确！！！");
                return modelAndView;
            }

        }

        //根据
        modelAndView.setViewName("index");
        //认证成功，将用户名存入session中
//        session.setAttribute("username",user.getUsername());
//        modelAndView.addObject("username",session.getAttribute("user"));
//        System.out.println(currentUser);
        return modelAndView;
    }



    /**
     * 退出登陆
     *
     * @return
     */
    @RequestMapping(value = "/logout")
    public ModelAndView logout() {
        // 获取当前执行的用户
        Subject currentUser = SecurityUtils.getSubject();
        //执行退出
        currentUser.logout();
        //跳转到登录界面
        modelAndView.setViewName("login");
        return modelAndView;
    }
}
